
package edu.weber.bookstore.controllers;

import edu.weber.bookstore.database.UserCart;
import edu.weber.bookstore.database.UserCartBook;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 
 * 
 */
public class UserCartBooksController extends AppController
{
	/**
	 * Page to add an item to a cart
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "/UserCartBooks/add")
	public String add(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String sessionId = AppController.getSessionId(request);
		UserCart uc = UserCart.find(sessionId);
		if(uc == null)
		{
			uc = new UserCart(sessionId);
			uc.save();
		}
		
		int book_id = Integer.parseInt(request.getParameter("book_id"));
		int qty = Integer.parseInt(request.getParameter("qty"));
		
		uc.addUserCartBook(new UserCartBook(uc.getId(), qty, book_id));
		
		uc.save();
		
		return "redirect:/UserCarts/index";
	}
	
	/**
	 * Page to update an item to a cart
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "/UserCartBooks/edit/")
	public String edit(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		int id = Integer.parseInt(request.getParameter("id"));
		UserCartBook ucb = UserCartBook.find(id);
		if(ucb != null)
		{
			int qty = Integer.parseInt(request.getParameter("qty"));
			ucb.setQty(qty);
			ucb.save();
		}
		return "redirect:/UserCarts/index";
	}
	
	/**
	 * Page to remove an item from a cart.
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "/UserCartBooks/delete/")
	public String  delete(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		int id = Integer.parseInt(request.getParameter("id"));
		UserCartBook ucb = UserCartBook.find(id);
		if(ucb != null)
		{
			ucb.delete();
		}
		return "redirect:/UserCarts/index";
	}
}
